#include "LoginWidget.h"
#include "ui_LoginWidget.h"
#include <QSqlQuery>
#include <DebugTool.h>
#include <QMessageBox>
#include <QTimer>
LoginWidget::LoginWidget(QWidget *parent) :
                                            QWidget(parent),
                                            ui(new Ui::LoginWidget)
{
  ui->setupUi(this);
  this->setWindowModality (Qt::ApplicationModal);
  this->setAttribute (Qt::WA_StyleSheet);
}

LoginWidget::~LoginWidget()
{
  delete ui;
}

// 点击确定按钮，查询数据
void LoginWidget::on_buttonBox_accepted()
{
  QString name = ui->edt_name->text ();
  QString pwd = ui->edt_pwd->text ();
  QString sql;
  bool admin = ui->chk_admin->isChecked ();
  if(admin)
     sql = QString("select id,pwd from manager where id =='%1';").arg (name);
  else
    sql =  QString("select id,pwd,loan,max from User where id =='%1';").arg(name);
//  cout << sql;
  QSqlQuery query;
  query.exec (sql);
  if(query.next ()){
//    cout << query.value (0).toString () << query.value (1).toString ();
    if(pwd == query.value (1)){
      int loan = admin ? 0 : query.value (2).toInt ();
      int max  = admin ? 0 : query.value (3).toInt ();
      QTimer::singleShot (500,[this,name,loan,max]{
        this->close ();
        emit login (name,ui->chk_admin->isChecked (),loan,max);
      } );
    }
  }
  else{
    QMessageBox::information (this,"错误","无此用户");
  }
}

// 点击取消按钮，关闭窗口
void LoginWidget::on_buttonBox_rejected()
{
  this->close ();
}
